package com.wclass.interceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ace on 2017/9/8.
 */
public class BaseContextHandler {
    public static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    public static final String CONTEXT_KEY_USER_ID = "currentUserId";
    public static final String CONTEXT_KEY_USERNAME = "currentUserName";
    public static final String CONTEXT_KEY_USER_NAME = "currentUser";
    public static final String CONTEXT_KEY_USER_SYSTEM = "currentSystem";
    public static final String CONTEXT_KEY_USER_TOKEN = "currentUserToken";

    public static void set(String key, Object value) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        map.put(key, value);
    }

    public static Object get(String key) {
        Map<String, Object> map = threadLocal.get();
        if (map == null) {
            map = new HashMap<String, Object>();
            threadLocal.set(map);
        }
        return map.get(key);
    }

    public static Long getUserID() {
        Object value = get(CONTEXT_KEY_USER_ID);
        return Long.parseLong(returnObjectValue(value));
    }


    public static String getUsername() {
        Object value = get(CONTEXT_KEY_USERNAME);
        return returnObjectValue(value);
    }


    public static String getName() {
        Object value = get(CONTEXT_KEY_USER_NAME);
        return (String) value;
    }

    public static String getSystem() {
        Object value = get(CONTEXT_KEY_USER_SYSTEM);
        return (String) value;
    }

    public static void setSystem(String system) {
        set(CONTEXT_KEY_USER_SYSTEM, system);
    }

    public static void setToken(String token) {
        set(CONTEXT_KEY_USER_TOKEN, token);
    }

    public static void setName(String name) {
        set(CONTEXT_KEY_USER_NAME, name);
    }

    public static void setUserID(String userID) {
        set(CONTEXT_KEY_USER_ID, userID);
    }

    public static void setUsername(String username) {
        set(CONTEXT_KEY_USERNAME, username);
    }

    private static String returnObjectValue(Object value) {
        return value == null ? null : value.toString();
    }

    public static void remove() {
        threadLocal.remove();
    }

}
